from PyPDF2 import PdfFileMerger
import os
import time
import sys

def merge_pdf(target_path, outpath=None):
    """
    将一个文件夹内的所有pdf合成为一个pdf
    :param target_path:     合并文件所在文件夹路径
    :param outpath:         [optional]输出文件路径，默认为合并文件所在文件夹路径
    :return:                None
    """
    pdf_lst = [f for f in os.listdir(target_path) if f.endswith('.pdf')]
    pdf_lst.sort()
    pdf_lst = [os.path.join(target_path, filename) for filename in pdf_lst]

    file_merger = PdfFileMerger(strict=False)
    for pdf in pdf_lst:
        file_merger.append(pdf)

    output_filename = "./merge_" + str(int(time.time())) + ".pdf"
    if outpath is None:
        outpath = os.path.join(target_path, output_filename)
    else:
        outpath = os.path.join(outpath, output_filename)
    file_merger.write(outpath)

if __name__ == '__main__':
    if len(sys.argv) == 1:
        print("Error：请输入参数 ")
        print("合并文件所在文件夹路径，[输出文件路径，默认为合并文件所在文件夹路径]")
    elif len(sys.argv) == 2:
        merge_pdf(sys.argv[1])
    elif len(sys.argv) == 3:
        merge_pdf(sys.argv[1], sys.argv[2])
    else:
        print("Error：请正确输入参数 ")
        print("合并文件所在文件夹路径，[输出文件路径，默认为合并文件所在文件夹路径]")
